<template>
	<a-card title="我的预约" :body-style="{ padding: '0' }">
		<div>
			<!-- 预约状态筛选 -->
			<div class="select-container">
				预约状态：
				<a-select
					v-model:value="selectedStatus"
					placeholder="选择预约状态"
					style="width: 200px"
					@change="handleStatusChange"
				>
					<a-select-option value="">全部</a-select-option>
					<a-select-option value="pending">待看房</a-select-option>
					<a-select-option value="rejected">已拒绝</a-select-option>
					<a-select-option value="expired">已过期</a-select-option>
					<a-select-option value="cancel">已取消</a-select-option>
				</a-select>
			</div>

			<!-- 表格显示 -->
			<a-table :columns="columns" :data-source="filteredAppointments" :pagination="false" :row-key="'id'" bordered>
				<template #bodyCell="{ column, record }">
					<!-- 房源图片 -->
					<template v-if="column.key === 'houseImage'">
						<img :src="record.houseImage" alt="房源图片" style="width: 110px; height: 86px; object-fit: cover" />
					</template>
					<!-- 房源类型 -->
					<template v-if="column.key === 'houseType'">
						{{ record.houseType === '1房0厅1卫' ? '单间' : record.houseType }}
					</template>
					<!-- 房东姓名 -->
					<template v-if="column.key === 'landlordName'">
						{{ record.landlordName }}
					</template>
					<!-- 房东联系电话 -->
					<template v-if="column.key === 'landlordPhone'">
						{{ record.landlordPhone }}
					</template>
					<!-- 预约时间 -->
					<template v-if="column.key === 'appointmentDate'">
						{{ formatAppointmentDateRange(record) }}
					</template>
					<!-- 预约状态 -->
					<template v-if="column.key === 'appointmentStatus'">
						{{ getStatus(record.appointmentStatus) }}
					</template>
					<!-- 预约备注 -->
					<template v-if="column.key === 'remarks'">
						<div style="width: 100px; white-space: normal; word-break: break-all">
							{{ record.remarks === 'changed' ? '变更时间' : record.remarks }}
						</div>
					</template>
					<!-- 操作列 -->
					<template v-if="column.key === 'action'">
						<a @click="goToDetails(record.houseId)">详情</a>
						<a
							v-if="
								!(record.remarks === '变更时间') &&
								!(record.appointmentStatus === 'rejected') &&
								!(record.appointmentStatus === 'expired') &&
								!(record.appointmentStatus === 'cancel')
							"
							style="margin-left: 1rem"
							@click="changeTime(record)"
						>
							变更
						</a>
						<!-- 取消按钮 -->
						<a
							v-if="record.appointmentStatus === 'pending'"
							style="margin-left: 1rem"
							@click="confirmCancelAppointment(record)"
						>
							取消
						</a>
					</template>
				</template>
			</a-table>

			<!-- 分页器 -->
			<a-pagination
				:current="pagination.current"
				:page-size="pagination.pageSize"
				:total="pagination.total"
				:page-size-options="['5', '10', '20', '50']"
				@change="handlePageChange"
				@showSizeChange="handlePageSizeChange"
				class="pagination"
				:show-total="(total, range) => `${range[0]}-${range[1]} 共 ${total} 条`"
				:locale="{ items_per_page: '条/页' }"
			></a-pagination>
		</div>

		<!-- 取消预约的确认模态框 -->
		<a-modal
			v-model:visible="cancelAppointmentVisible"
			title="取消预约"
			@ok="cancelAppointment"
			@cancel="cancelCancelAppointment"
			ok-text="确认"
			cancel-text="取消"
			centered
			width="400px"
		>
			<p>确定取消该预约吗？</p>
		</a-modal>

		<!-- 变更时间模态框 -->
		<a-modal
			v-model:visible="changeTimeVisible"
			:title="modalTitle"
			@ok="confirmChangeTime"
			@cancel="cancelChangeTime"
			ok-text="确认变更"
			cancel-text="取消"
			:footer="null"
			centered
			width="400px"
		>
			<!-- 第一步：选择日期 -->
			<div v-if="reservationStep === 1">
				<div class="date-list">
					<a-button
						v-for="(date, index) in availableDates"
						:key="index"
						style="margin: 5px"
						@click="selectDate(date)"
						:type="selectedDate === date ? 'primary' : 'default'"
					>
						{{ formatDate(date) }}
					</a-button>
				</div>
			</div>

			<!-- 第二步：选择具体时段 -->
			<div v-else-if="reservationStep === 2">
				<div class="time-slot-list" style="display: flex; flex-wrap: wrap; justify-content: center">
					<a-button
						v-for="(slot, index) in availableTimeSlots"
						:key="index"
						:disabled="slot.status !== 'available'"
						:type="selectedSchedule && selectedSchedule.id === slot.id ? 'primary' : 'default'"
						style="margin: 5px"
						@click="selectTimeSlot(slot)"
					>
						{{ slot.startTime }} - {{ slot.endTime }}
					</a-button>
				</div>
				<div style="text-align: center; margin-top: 20px">
					<a-button @click="backToStep1" style="margin-right: 10px">返回</a-button>
					<a-button type="primary" @click="confirmChangeTime">确定</a-button>
				</div>
			</div>
		</a-modal>
	</a-card>
</template>

<script>
	import userApi from '@/api/userApi';
	import { message, Modal } from 'ant-design-vue';
	import dayjs from 'dayjs';

	export default {
		data() {
			return {
				// 表格列配置（已增加预约时间列）
				columns: [
					{ title: '房源图片', dataIndex: 'houseImage', key: 'houseImage', width: 100 },
					{ title: '房源类型', dataIndex: 'houseType', key: 'houseType', width: 130 },
					{ title: '房东姓名', dataIndex: 'landlordName', key: 'landlordName', width: 140 },
					{ title: '房东联系电话', dataIndex: 'landlordPhone', key: 'landlordPhone', width: 120 },
					{ title: '预约时间', dataIndex: 'appointmentDate', key: 'appointmentDate', width: 130 },
					{ title: '预约状态', dataIndex: 'appointmentStatus', key: 'appointmentStatus', width: 120 },
					{ title: '预约备注', dataIndex: 'remarks', key: 'remarks', width: 110 },
					{ title: '操作', dataIndex: 'action', key: 'action', width: 220 }
				],
				// 预约数据源
				appointments: [],
				// 分页器参数
				pagination: {
					current: 1,
					pageSize: 10,
					total: 0
				},
				// 预约状态筛选
				selectedStatus: '',
				// 变更时间模态框相关
				changeTimeVisible: false,
				appointmentDate: null,
				currentRecord: null,
				// 房东的所有可预约档期
				availableSchedules: [],
				// 当前步骤（1：选择日期，2：选择时段）
				reservationStep: 1,
				// 选择的日期和时段
				selectedDate: null,
				selectedSchedule: null,
				// 房东可用的日期
				availableDates: [],
				// 可用的时段
				availableTimeSlots: [],
				// 取消预约相关
				cancelAppointmentVisible: false
			};
		},
		computed: {
			// 过滤预约数据
			filteredAppointments() {
				if (!this.selectedStatus) {
					return this.appointments;
				}
				return this.appointments.filter((item) => item.appointmentStatus === this.selectedStatus);
			},
			// 模态框标题根据步骤变化
			modalTitle() {
				return this.reservationStep === 1 ? '变更看房日期' : '选择具体时段';
			}
		},
		methods: {
			// 加载预约数据
			loadAppointments() {
				userApi
					.getReserveHouses(this.pagination.current, this.pagination.pageSize, this.selectedStatus)
					.then((res) => {
						if (res.code === 200) {
							this.appointments = res.data.appointments;
							this.pagination.total = res.data.total;
						} else {
							message.error(res.message || '查询失败');
						}
					})
					.catch((error) => {
						console.error('获取预约数据失败:', error);
						message.error('获取预约数据失败');
					});
			},
			// 加载房东可用的档期
			loadAvailableSchedules(landlordId) {
				userApi
					.getLandlordSchedules(landlordId)
					.then((res) => {
						if (res.code === 200) {
							this.availableSchedules = res.data;
							this.availableDates = Array.from(new Set(res.data.map((schedule) => schedule.scheduleDate)));
						} else {
							message.error(res.message || '获取房东档期失败');
						}
					})
					.catch((error) => {
						console.error('获取房东档期失败:', error);
						message.error('获取房东档期失败');
					});
			},
			// 分页页码变化
			handlePageChange(page) {
				this.pagination.current = page;
				this.loadAppointments();
			},
			// 分页每页条数变化
			handlePageSizeChange(current, size) {
				this.pagination.pageSize = size;
				this.pagination.current = 1;
				this.loadAppointments();
			},
			// 预约状态筛选变化
			handleStatusChange(value) {
				this.selectedStatus = value;
				this.pagination.current = 1;
				this.loadAppointments();
			},
			// 审核状态转换为中文
			getStatus(status) {
				const statusMap = {
					pending: '待看房',
					expired: '已过期',
					cancel: '已取消',
					rejected: '已拒绝'
				};
				return statusMap[status] || status;
			},
			// 显示变更时间模态框
			changeTime(record) {
				this.currentRecord = record; // 确保 currentRecord 被正确赋值
				this.changeTimeVisible = true;
				this.reservationStep = 1; // 重置为第一步（选择日期）
				this.loadAvailableSchedules(record.landlordId); // 加载房东的可预约档期
			},
			// 格式化日期
			formatDate(date) {
				return dayjs(date).format('YYYY-MM-DD');
			},
			// 选择日期
			selectDate(date) {
				this.selectedDate = date;
				this.reservationStep = 2;
				this.availableTimeSlots = this.availableSchedules.filter(
					(schedule) => schedule.scheduleDate === this.selectedDate
				);
			},
			// 选择时段
			selectTimeSlot(slot) {
				this.selectedSchedule = slot;
			},
			// 返回第一步
			backToStep1() {
				this.reservationStep = 1;
			},
			// 确认变更时间
			// 修改后的确认变更时间方法
			confirmChangeTime() {
				const record = this.currentRecord;
				const selected = this.selectedSchedule;

				if (!selected) {
					message.error('请选择时段');
					return;
				}

				const self = this; // 保存当前vue实例的引用
				Modal.confirm({
					title: '确认变更预约时间吗？',
					okText: '确认',
					cancelText: '取消',
					async onOk() {  // 使用async函数处理异步操作
						try {
							const res = await userApi.changeAppointmentTime(
								record.id,
								record.scheduleId,
								selected.id,
								self.formatAppointmentDateRange({  // 直接使用格式化方法
									appointmentDate: selected.scheduleDate,
									startTime: selected.startTime
								})
							);

							if (res.code === 200) {
								message.success('预约时间变更成功');
								// 关闭模态框
								self.changeTimeVisible = false;
								// 重置选择状态
								self.reservationStep = 1;
								self.selectedDate = null;
								self.selectedSchedule = null;
								// 刷新数据
								await self.loadAppointments();
								// 重新加载可用档期（防止缓存旧数据）
								await self.loadAvailableSchedules(record.landlordId);
							} else {
								message.error(res.message || '变更失败');
							}
						} catch (error) {
							console.error('变更失败:', error);
							message.error('变更请求失败');
						}
					}
				});
			},
			// 取消变更时间
			cancelChangeTime() {
				this.changeTimeVisible = false;
			},
			// 格式化显示预约时间区间
			formatAppointmentDateRange(record) {
				const startTime = dayjs(record.appointmentDate).format('YYYY-MM-DD HH:mm');
				const endTime = dayjs(record.appointmentDate).add(2, 'hour').format('HH:mm'); // 假设预约时长为2小时
				return `${startTime}-${endTime}`; // 显示为 "2025-03-20 11:00-13:00"
			},
			goToDetails(houseId) {
				window.open(`/house-details/${houseId}`, '_blank');
			},
			// 取消预约的确认弹窗
			confirmCancelAppointment(record) {
				this.currentRecord = record;
				this.cancelAppointmentVisible = true; // 显示确认取消的模态框
			},
			// 取消预约
			cancelAppointment() {
				const record = this.currentRecord;
				// 调用取消预约接口
				userApi
					.cancelAppointment(record.id)
					.then((res) => {
						if (res.code === 200) {
							message.success('预约已取消');
							this.cancelAppointmentVisible = false;
							this.loadAppointments(); // 刷新预约列表
						} else {
							message.error(res.message || '取消预约失败');
						}
					})
					.catch((error) => {
						console.error('取消预约时发生错误:', error);
						message.error('取消预约失败');
					});
			},
			// 关闭取消预约的模态框
			cancelCancelAppointment() {
				this.cancelAppointmentVisible = false;
			}
		},
		mounted() {
			this.loadAppointments();
		}
	};
</script>

<style scoped>
	.pagination {
		margin: 1rem 0;
		text-align: right;
	}

	.select-container {
		align-items: center;
		margin: 1rem 0;
		display: flex;
		text-align: center;
		justify-content: flex-end;
		font-size: 15px;
	}
</style>
